package com.smalls.redshoes.ui.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.smalls.newvideotwo.base.BaseActivity;
import com.smalls.newvideotwo.db.Category;
import com.smalls.newvideotwo.mvp.bean.MovieDetail;
import com.smalls.newvideotwo.mvp.beanResult.GetColumnsResult;
import com.smalls.newvideotwo.mvp.beanResult.GetColumnsResultData;
import com.smalls.newvideotwo.mvp.beanResult.GetHotMovieResult;
import com.smalls.newvideotwo.mvp.http.constants.PortalErr;
import com.smalls.newvideotwo.mvp.http.constants.PortalErrUtil;
import com.smalls.newvideotwo.mvp.presenter.GetColumnsPresenter;
import com.smalls.newvideotwo.mvp.presenter.GetMovieByCategoryPresenter;
import com.smalls.newvideotwo.mvp.view.IGetColumnsView;
import com.smalls.newvideotwo.mvp.view.IGetHotMovieView;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;
import com.smalls.redshoes.R;
import com.smalls.redshoes.adapter.RSVodCategoryAdapter;
import com.smalls.redshoes.adapter.RSVodDetailContentAdapter;
import com.smalls.redshoes.ui.widget.GrapeGridview;
import com.smalls.redshoes.ui.widget.LoadingView;
import com.smalls.redshoes.ui.widget.OrderStateDialog;
import com.smalls.redshoes.util.AnimationUtil;
import com.smalls.redshoes.util.ViewUtils;
import com.uking.ukingmodule.ukingjnic;
import com.uking.util.VKConstant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class RSVodActivity extends BaseActivity implements View.OnClickListener, IGetHotMovieView, IGetColumnsView, View.OnFocusChangeListener {
    private static String TAG = Constant.baddcoolio2tag?Constant.TAGPREFIXSTR + RSVodActivity.class.getSimpleName():RSVodActivity.class.getSimpleName();
    private ImageView iv_vod_category_collect;
    private ImageView iv_vod_category_history;
    private ListView lv_vod_category;
    private int mCategoryPosition=-1;
    private View mPreView;
    private RSVodCategoryAdapter mRSVodCategoryAdapter;
    private GrapeGridview ggv_vod_category_content;
    protected ImageLoader imageLoader = ImageLoader.getInstance();
    private LinearLayout ll_category_content_title;
    private RSVodDetailContentAdapter mContentAdapter;
    private int mGridPosition=-1;
    private static final int mOnePageMax = 200;
    private int mStart = 0;
    private int mEnd = mOnePageMax-1;
    private View tag;
    private TextView tv_category_name;
    private TextView tv_total;
    private List<MovieDetail> mMovieList = new ArrayList<MovieDetail>();
    private List<Category> mCategoryList = new ArrayList<Category>();
    private Handler mHandler = new Handler();
    private GetMovieByCategoryPresenter columnContentPresenter = new GetMovieByCategoryPresenter(this);
    private LoadingView vod_loading_view;
    private View mHisCollectFocusView = null;

    private AdapterView.OnItemClickListener vodOnItemClickListener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            LogUtil.d(TAG,"vodOnItemClickListener pos="+position);
            if(position>=0&&position<mMovieList.size()) {
                Intent intent = new Intent();
                intent.setClass(RSVodActivity.this, VodDetailActivity.class);
                intent.putExtra("get",false);
                intent.putExtra("movie_id",mMovieList.get(position));
                intent.putExtra("category_id",mMovieList.get(position).getCategory_id());
                startActivity(intent);
            }
        }
    };
    private AdapterView.OnItemSelectedListener vodOnItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            LogUtil.d(TAG,"vodOnItemSelectedListener onItemSelected position="+position);
            mGridPosition = position;
            if (ggv_vod_category_content.hasFocus() && view != null) {
                view.findViewById(R.id.rl_content).setBackgroundResource(R.drawable.rs_vod_content_bg);
                AnimationUtil.scale(view, 1.1f);
            }
            if (view != tag) {
                if (tag != null) {
                    tag.findViewById(R.id.rl_content).setBackgroundResource(0);
                    AnimationUtil.scaleBack(tag, 1.1f);
                }
                tag = view;
            }
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    };
    private AbsListView.OnScrollListener vodOnScrollListener = new AbsListView.OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
                case 0 /*0*/:
                    imageLoader.resume();
                    return;
                case 1 /*1*/:
                    imageLoader.pause();
                    return;
                case 2 /*2*/:
                    imageLoader.pause();
                    return;
                default:
                    return;
            }
        }

        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    };
    public void changeCategory(int category) {
        if (category != mCategoryPosition) {
            mCategoryPosition = category;
            hintCategoryTitle();
            clearData();
            mHandler.post(getMovie);
        }
    }
    public void clearData() {
        mStart = 0;
        mEnd = mOnePageMax - 1;
        this.mContentAdapter.clear();
    }

    private Runnable initMovieAdapter = new Runnable() {
        @Override
        public void run() {
            initAdapterData(mMovieList);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    vod_loading_view.setVisibility(View.GONE);
                }
            });
        }
    };

    private Runnable initCategoryAdapter = new Runnable() {
        @Override
        public void run() {
            mRSVodCategoryAdapter.setData(mCategoryList);
            setListItemFocus();
        }
    };

    private Runnable getMovie = new Runnable() {
        @Override
        public void run() {
            if(mCategoryList!=null&&mCategoryList.size()>0
                    &&mCategoryPosition<mCategoryList.size()) {
                vod_loading_view.setVisibility(View.VISIBLE);
                if(columnContentPresenter!=null) {
                    columnContentPresenter.Abort();
                    columnContentPresenter.request(false, mCategoryList.get(mCategoryPosition), mStart, mEnd);
                }
            }
        }
    };

    public void initAdapterData(List<MovieDetail> listProgramModel) {
        this.mContentAdapter.setData(listProgramModel);
    }

    @Override
    public void onSucceedGetHotMovie(GetHotMovieResult movieDetail) {
        if (movieDetail == null
                || movieDetail.getData() == null) {

            PortalErrUtil.getInstance().setErrCode(PortalErr.NO_ASSOCIATED_PORTAL);
            //showEpgErrorMessge();
        } else {
            mMovieList.addAll(movieDetail.getData());
            if(movieDetail.getData().size()<mOnePageMax) {
                mHandler.post(initMovieAdapter);
            } else {
                mStart = mEnd+1;
                mEnd += mOnePageMax;
                columnContentPresenter.request(false, mCategoryList.get(mCategoryPosition), mStart, mEnd);
            }
            movieDetail.getData().clear();
        }
    }

    @Override
    public void showErrDialogGetHotMovie(String str) {
        vod_loading_view.setVisibility(View.GONE);
    }

    @Override
    public void onSucceedGetColumnContents(GetColumnsResult getColumnContentsResult, int i) {
        if (getColumnContentsResult != null
                && getColumnContentsResult.getData() != null
                && getColumnContentsResult.getData().size() > 0) {

            Collections.sort(getColumnContentsResult.getData(),new Comparator<GetColumnsResultData>(){
                public int compare(GetColumnsResultData arg0, GetColumnsResultData arg1) {
                    if(arg0.getSequence()>arg1.getSequence()) {
                        return 1;
                    } else if(arg0.getSequence()==arg1.getSequence()) {
                        return 0;
                    } else {
                        return -1;
                    }
                }
            });
            for (int k = 0; k < getColumnContentsResult.getData().size(); k++) {
                GetColumnsResultData data = getColumnContentsResult.getData().get(k);
                if (data != null
                        &&data.getType().equals("movie")) {
                    Log.i(TAG,"onSucceedGetColumnContents title="+data.getTitle()+" Category_id="+data.getCategory_id()+
                            " Parent_id="+data.getParent_id());
                    Category category = new Category();
                    category.setCategory_id(data.getCategory_id());
                    category.setTitle(data.getTitle());
                    category.setParent_id(data.getParent_id());
                    category.setShort_title(data.getShort_title());
                    category.setSubtitle(data.getSubtitle());
                    category.setDepth(data.getDepth());
                    category.setState(1);
                    mCategoryList.add(category);
                }
            }
            mHandler.post(initCategoryAdapter);
        }
    }

    @Override
    public void showErrDialogGetColumnContents(String str, int i) {

    }

    @Override
    public void onFocusChange(View view, boolean b) {
        if(view.getId()==R.id.iv_vod_category_collect
                ||view.getId()==R.id.iv_vod_category_history) {
            if(b) {
                mHisCollectFocusView = view;
            }
        }
    }

    public class categoryOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            LogUtil.d(TAG,"onItemSelected position="+position);
            if (isListViewFocus() && view != null) {
                focusItem(view);
            }
            if (mPreView != view) {
                if (mPreView != null) {
                    unfocusItem(mPreView);
                }
                mPreView = view;
            }
            if(position>=0&&position<mCategoryList.size()
                    &&position!=mCategoryPosition) {
                changeCategory(position);
            }
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    }

    public boolean isListViewFocus() {
        return this.lv_vod_category.hasFocus();
    }

    public int onSetContentView() {
        return R.layout.rs_activity_vod;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView(savedInstanceState);
        ukingjnic ukingjni = ukingjnic.getInstance();
        String result = ukingjni.initDownloadModul(VKConstant.TYPE_VOD, VKConstant.DEFAULT_VOD_PORT);
    }

    protected void initView(Bundle savedInstanceState) {
        this.lv_vod_category = (ListView) findViewById(R.id.lv_vod_category);
        this.iv_vod_category_history = (ImageView) findViewById(R.id.iv_vod_category_history);
        this.iv_vod_category_collect = (ImageView) findViewById(R.id.iv_vod_category_collect);
        this.mRSVodCategoryAdapter = new RSVodCategoryAdapter(this);
        this.lv_vod_category.setAdapter(this.mRSVodCategoryAdapter);
        this.lv_vod_category.setSelector(new ColorDrawable(0));
        this.tv_category_name = (TextView) findViewById(R.id.tv_category_name);
        this.tv_total = (TextView) findViewById(R.id.tv_total);
        this.ll_category_content_title = (LinearLayout) findViewById(R.id.ll_category_content_title);
        this.ggv_vod_category_content = (GrapeGridview) findViewById(R.id.ggv_vod_category_content);
        this.mContentAdapter = new RSVodDetailContentAdapter(this, this.imageLoader);
        this.ggv_vod_category_content.setAdapter(this.mContentAdapter);
        this.ggv_vod_category_content.setSelector(new ColorDrawable(0));
        vod_loading_view = (LoadingView) findViewById(R.id.vod_loading_view);
        setListener();
        //processLogic(savedInstanceState);
        clearRestFocus();
    }

    protected void setListener() {
        this.iv_vod_category_history.setOnClickListener(this);
        this.iv_vod_category_collect.setOnClickListener(this);
        this.iv_vod_category_history.setOnFocusChangeListener(this);
        this.iv_vod_category_collect.setOnFocusChangeListener(this);
        this.lv_vod_category.setOnItemSelectedListener(new categoryOnItemSelectedListener());
        this.ggv_vod_category_content.setOnScrollListener(this.vodOnScrollListener);
        this.ggv_vod_category_content.setOnItemClickListener(this.vodOnItemClickListener);
        this.ggv_vod_category_content.setOnItemSelectedListener(this.vodOnItemSelectedListener);
        this.mContentAdapter.setOnIsShowDelete(new RSVodDetailContentAdapter.ISShowDelete() {
            public boolean isShowDelete() {
                return false;
            }
        });
    }


    public void onClick(View v) {
        int i = v.getId();
        Intent intent=null;
        if (i == R.id.iv_vod_category_history) {
            intent = new Intent();
            intent.setClass(this,HistoryActivity.class);
            intent.putExtra("category_select",101);
        } else if (i == R.id.iv_vod_category_collect) {
            intent = new Intent();
            intent.setClass(this,HistoryActivity.class);
            intent.putExtra("category_select",102);
        }

        if(intent!=null) {
            startActivity(intent);
        }
    }

    protected void processLogic(Bundle savedInstanceState) {
        GetColumnsPresenter getColumnsPresenter = new GetColumnsPresenter(this);
        getColumnsPresenter.requestData("movie",false);
    }

    public void onLowMemory() {
        super.onLowMemory();
        ImageLoader.getInstance().clearMemoryCache();
    }

    public void onDestroy() {
        super.onDestroy();
        ImageLoader.getInstance().clearMemoryCache();
        ukingjnic ukingjni = ukingjnic.getInstance();
        ukingjni.destroyDlownloadModul(VKConstant.TYPE_VOD);
        System.gc();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        View view = getCurrentFocus();
        if(view==null) {
            return true;
        }
        LogUtil.d(TAG,"onKeyDown keyCode="+keyCode+" view="+view);
        if(view.getId()==R.id.ll_category_name
                &&view.getId()==R.id.lv_vod_category
                &&vod_loading_view.getVisibility()==View.VISIBLE) {
            LogUtil.d(TAG,"no need to deal key Event");
            return true;
        }
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (isListViewFocus()) {
                    return true;
                }
                if (isGridViewFocus() && getPosition() % 4 == 0) {
                    clearGridItemFocus();
                    setListItemFocus();
                    setRestFocus();
                    return true;
                } else if (isHistoryFocus()) {
                    setListItemFocus();
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if(view.getId()==R.id.ll_category_name
                        ||view.getId()==R.id.lv_vod_category) {
                    if(isGridViewOK()) {
                        clearListItemFocus();
                        setGridItemFocus();
                        return true;
                    } else {
                        setRestFocus();
                        historyRequestFocus();
                        return true;
                    }
                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                if (isGridViewFocus() && getPosition() < 4) {
                    clearGridItemFocus();
                    setRestFocus();
                    if(mHisCollectFocusView!=null) {
                        mHisCollectFocusView.requestFocus();
                        return true;
                    }
                }
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if(view.getId()==R.id.iv_vod_category_collect
                        ||view.getId()==R.id.iv_vod_category_history) {
                    clearRestFocus();
                    setGridItemFocus();
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_MENU:
                LogUtil.d(TAG,"start OrderStateActivity");
                final OrderStateDialog confirmDialog = new OrderStateDialog(RSVodActivity.this, com.smalls.newvideotwo.R.style.dialog);
                confirmDialog.show();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void requestListViewFocus() {
        this.lv_vod_category.setFocusable(true);
        this.lv_vod_category.requestFocus();
    }

    private void unRequestListViewFocus() {
        this.lv_vod_category.clearFocus();
        this.lv_vod_category.setFocusable(false);
    }

    private void focusItem(View view) {
        if(view!=null) {
            LinearLayout ll_category_name = (LinearLayout) view.findViewById(R.id.ll_category_name);
            ViewGroup.LayoutParams lp = view.getLayoutParams();
            lp.width = ViewUtils.DipToPixels(this, 240.0f);
            ll_category_name.setLayoutParams(lp);
            ll_category_name.setPadding(0, 0, 0, 0);
            ll_category_name.setGravity(17);
            ll_category_name.setBackgroundResource(R.drawable.rs_vod_category_focus);
        }
    }

    private void unfocusItem(View view) {
        if(view!=null) {
            LinearLayout ll_category_name = (LinearLayout) view.findViewById(R.id.ll_category_name);
            ViewGroup.LayoutParams lp = view.getLayoutParams();
            lp.width = ViewUtils.DipToPixels(this, 190.0f);
            ll_category_name.setLayoutParams(lp);
            ll_category_name.setPadding(ViewUtils.DipToPixels(this, 40.0f), 0, 0, 0);
            ll_category_name.setGravity(16);
            ll_category_name.setBackgroundResource(R.drawable.rs_vod_category_unfocus);
        }
    }

    private String setStringFormat(int num) {
        return String.format(getResources().getString(R.string.rs_vod_total), new Object[]{Integer.valueOf(num)});
    }

    public void showCategoryTitle(String name, int total) {
        this.tv_total.setText(setStringFormat(total));
        this.tv_category_name.setText(name);
        this.ll_category_content_title.setVisibility(View.VISIBLE);
    }

    public void hintCategoryTitle() {
        this.ll_category_content_title.setVisibility(View.INVISIBLE);
    }

    public int getPosition() {
        return this.mGridPosition;
    }

    public void setPosition(int position) {
        this.mGridPosition = position;
    }

    public boolean isGridViewOK() {
        if (this.ggv_vod_category_content == null || this.ggv_vod_category_content.getCount() <= 0) {
            return false;
        }
        return true;
    }

    public boolean isGridViewFocus() {
        return this.ggv_vod_category_content.hasFocus();
    }

    public void clearGridItemFocus() {
        if (this.ggv_vod_category_content != null && this.ggv_vod_category_content.hasFocus() && this.ggv_vod_category_content.getCount() > 0) {
            View view = this.ggv_vod_category_content.getSelectedView();
            if (view != null) {
                view.findViewById(R.id.rl_content).setBackgroundResource(0);
                AnimationUtil.scaleBack(view, 1.1f);
                view.setSelected(false);
            }
            unRequestGridViewFocus();
        }
    }

    public void setGridItemFocus() {
        requestGridViewFocus();
        this.ggv_vod_category_content.setSelection(this.mGridPosition);
        View view = this.ggv_vod_category_content.getSelectedView();
        if (view != null) {
            view.findViewById(R.id.rl_content).setBackgroundResource(R.drawable.rs_vod_content_bg);
            AnimationUtil.scale(view, 1.1f);
            view.setSelected(true);
            this.tag = view;
        }
    }

    private void requestGridViewFocus() {
        this.ggv_vod_category_content.setFocusable(true);
        this.ggv_vod_category_content.requestFocus();
    }

    private void unRequestGridViewFocus() {
        this.ggv_vod_category_content.clearFocus();
        this.ggv_vod_category_content.setFocusable(false);
    }

    public boolean isHistoryFocus() {
        return this.iv_vod_category_history.hasFocus();
    }

    public void historyRequestFocus() {
        this.iv_vod_category_history.requestFocus();
    }

    public boolean isCollectFocus() {
        return this.iv_vod_category_collect.hasFocus();
    }

    public void collectRequestFocus() {
        this.iv_vod_category_collect.requestFocus();
    }

    public void setRestFocus() {
        this.iv_vod_category_history.setFocusable(true);
        this.iv_vod_category_collect.setFocusable(true);
    }

    public void clearRestFocus() {
        this.iv_vod_category_history.setFocusable(false);
        this.iv_vod_category_collect.setFocusable(false);
    }

    public void setListItemFocus() {
        if (this.lv_vod_category != null && this.lv_vod_category.getCount() > 0) {
            requestListViewFocus();
            focusItem(this.lv_vod_category.getSelectedView());
        }
    }

    public void clearListItemFocus() {
        if (this.lv_vod_category != null && this.lv_vod_category.getCount() > 0 && this.lv_vod_category.hasFocus()) {
            this.lv_vod_category.getSelectedView().findViewById(R.id.ll_category_name).setBackgroundResource(R.drawable.rs_vod_category_unfocus);
            unRequestListViewFocus();
        }
    }
}
